package com.android.xcalendar.activity;

import java.util.Date;

import com.android.xcalendar.R;
import com.android.xcalendar.model.Location;
import com.android.xcalendar.util.XCalendarAPIManager;
import com.android.xcalendar.util.XCalendarContentManager;

import android.R.integer;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.app.TimePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnCancelListener;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TimePicker;

public class EventDetailsActivity extends Activity {
	
	EditText editTitle, editDescription;
	Spinner spinnerLocation;
	Button btnUpdate, btnCancel;
	Button btnSetSDate, btnSetSTime,btnSetEDate, btnSetETime, btnSetRDate, btnSetRTime;
	String titleString, startString, endString, remindString, descriptionString, locationKeyString, url;
	XCalendarContentManager contentManager = XCalendarContentManager.getInstance();
	XCalendarAPIManager apiManager = XCalendarAPIManager.getInstance();	
	Date startTime = new Date();
	Date endTime = new Date();
	Date remindTime = new Date();
	static final int S_DATE_DIALOG_ID = 0;
	static final int S_TIME_DIALOG_ID = 1;
	static final int E_DATE_DIALOG_ID = 2;
	static final int E_TIME_DIALOG_ID = 3;
	static final int R_DATE_DIALOG_ID = 4;
	static final int R_TIME_DIALOG_ID = 5;
//    private int mYear;  
//    private int mMonth;  
//    private int mDay; 
//    private int mHour;  
//    private int mMinute;  
	private ProgressDialog pDialog;
	
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.eventdetails);
		
		pDialog = new ProgressDialog(this);
		editTitle = (EditText) findViewById(R.id.editTitle);
		editDescription = (EditText) findViewById(R.id.editDescription);
		btnUpdate = (Button) findViewById(R.id.button_update);
		btnCancel = (Button) findViewById(R.id.button_cancel);

		startTime = contentManager.getSelectedEvent().getStartTime();
		endTime = contentManager.getSelectedEvent().getEndTime();
		remindTime = contentManager.getSelectedEvent().getRemindTime();
		locationKeyString = contentManager.getSelectedEvent().getLocationKey();
		
		spinnerLocation = (Spinner)findViewById(R.id.newSpinnerLocation);
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item);
		int i = 0;
		int targetPos = 0;
		for(Location location:contentManager.getLocations()){
			adapter.add(location.getLocationName());
			if(location.getKey()==locationKeyString)
				targetPos = i;
			i++;
		}
		spinnerLocation.setPrompt("Select location:");
		spinnerLocation.setAdapter(adapter);
		spinnerLocation.setSelection(targetPos, true);
		
		editTitle.setText(contentManager.getSelectedEvent().getTitle());
		editDescription.setText(contentManager.getSelectedEvent().getDescription());
		
		btnSetSDate = (Button) findViewById(R.id.button_set_start_date);
		btnSetSDate.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				showDialog(S_DATE_DIALOG_ID);
			}
		});
		btnSetSTime = (Button) findViewById(R.id.button_set_start_time);
		btnSetSTime.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				showDialog(S_TIME_DIALOG_ID);
			}
		});
		btnSetEDate = (Button) findViewById(R.id.button_set_end_date);
		btnSetEDate.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				showDialog(E_DATE_DIALOG_ID);
			}
		});
		btnSetETime = (Button) findViewById(R.id.button_set_end_time);
		btnSetETime.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				showDialog(E_TIME_DIALOG_ID);
			}
		});
		btnSetRDate = (Button) findViewById(R.id.button_set_remind_date);
		btnSetRDate.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				showDialog(R_DATE_DIALOG_ID);
			}
		});
		btnSetRTime = (Button) findViewById(R.id.button_set_remind_time);
		btnSetRTime.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				showDialog(R_TIME_DIALOG_ID);
			}
		});
		
		btnSetSDate.setText(new StringBuilder().append(startTime.getDate()).append("-")
				.append(startTime.getMonth()+1).append("-").append(startTime.getYear()+1900));
		btnSetEDate.setText(new StringBuilder().append(endTime.getDate()).append("-")
				.append(endTime.getMonth()+1).append("-").append(endTime.getYear()+1900));
		btnSetRDate.setText(new StringBuilder().append(remindTime.getDate()).append("-")
				.append(remindTime.getMonth()+1).append("-").append(remindTime.getYear()+1900));
		btnSetSTime.setText(new StringBuilder().append(startTime.getHours()).append(":")
				.append(startTime.getMinutes()));
		btnSetETime.setText(new StringBuilder().append(endTime.getHours()).append(":")
				.append(endTime.getMinutes()));
		btnSetRTime.setText(new StringBuilder().append(remindTime.getHours()).append(":")
				.append(remindTime.getMinutes()));
			
		btnUpdate.setOnClickListener(updateListener);
		btnCancel.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
	}

	private OnDateSetListener setSDateListener = new OnDateSetListener() {
		public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
			startTime.setYear(year - 1900);
			startTime.setMonth(monthOfYear);
			startTime.setDate(dayOfMonth);
			btnSetSDate.setText(new StringBuilder().append(dayOfMonth).append("-")
					.append(monthOfYear+1).append("-").append(year));
		}
	};
	private OnTimeSetListener setSTimeListener = new OnTimeSetListener() {
		public void onTimeSet(TimePicker view, int hours, int minutes) {
			startTime.setHours(hours);
			startTime.setMinutes(minutes);
			btnSetSTime.setText(new StringBuilder().append(hours).append(":")
					.append(minutes));
		}
	};
	private OnDateSetListener setEDateListener = new OnDateSetListener() {
		public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
			endTime.setYear(year - 1900);
			endTime.setMonth(monthOfYear);
			endTime.setDate(dayOfMonth);
			btnSetEDate.setText(new StringBuilder().append(dayOfMonth).append("-")
					.append(monthOfYear+1).append("-").append(year));
		}
	};
	private OnTimeSetListener setETimeListener = new OnTimeSetListener() {
		public void onTimeSet(TimePicker view, int hours, int minutes) {
			endTime.setHours(hours);
			endTime.setMinutes(minutes);
			btnSetETime.setText(new StringBuilder().append(hours).append(":")
					.append(minutes));
		}
	};
	private OnDateSetListener setRDateListener = new OnDateSetListener() {
		public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
			remindTime.setYear(year - 1900);
			remindTime.setMonth(monthOfYear);
			remindTime.setDate(dayOfMonth);
			btnSetRDate.setText(new StringBuilder().append(dayOfMonth).append("-")
					.append(monthOfYear+1).append("-").append(year));
		}
	};
	private OnTimeSetListener setRTimeListener = new OnTimeSetListener() {
		public void onTimeSet(TimePicker view, int hours, int minutes) {
			remindTime.setHours(hours);
			remindTime.setMinutes(minutes);
			btnSetRTime.setText(new StringBuilder().append(hours).append(":")
					.append(minutes));			
		}
	};
	
    @Override  
    protected Dialog onCreateDialog(int id) {  
           switch (id) {  
           case S_DATE_DIALOG_ID:  
               return new DatePickerDialog(this, setSDateListener, startTime.getYear()+1900, startTime.getMonth(), startTime.getDate());  
           case S_TIME_DIALOG_ID:  
               return new TimePickerDialog(this, setSTimeListener, startTime.getHours(), startTime.getMinutes(), true);  
           case E_DATE_DIALOG_ID:  
               return new DatePickerDialog(this, setEDateListener, endTime.getYear()+1900, endTime.getMonth(), endTime.getDate());  
           case E_TIME_DIALOG_ID:  
               return new TimePickerDialog(this, setETimeListener, endTime.getHours(), endTime.getMinutes(), true);  
           case R_DATE_DIALOG_ID:  
               return new DatePickerDialog(this, setRDateListener, remindTime.getYear()+1900, remindTime.getMonth(), remindTime.getDate());  
           case R_TIME_DIALOG_ID:  
               return new TimePickerDialog(this, setRTimeListener, remindTime.getHours(), remindTime.getMinutes(), true);   
          }  
            return null;  
    }  
	
	private OnClickListener updateListener = new OnClickListener()
	{
		@Override
		public void onClick(View v) {
			titleString = editTitle.getText().toString();
			startString = String.valueOf(startTime.getTime());
			endString = String.valueOf(endTime.getTime());
			remindString = String.valueOf(remindTime.getTime());
			descriptionString = editDescription.getText().toString();
			
			int selectedP = spinnerLocation.getSelectedItemPosition();
			if(selectedP == android.widget.AdapterView.INVALID_POSITION)
				locationKeyString = "";
			else 
				locationKeyString = contentManager.getLocations().get(selectedP).getKey();
					
			url = "http://xiaoyitest.appspot.com/resources/EditEvent/userName="
				+ contentManager.getUserName() 
				+ "&eventKey=" + contentManager.getSelectedEvent().getKey()
				+ "&eventTitle=" + titleString
				+ "&eventDescription=" + descriptionString
				+ "&eventStart=" + startString
				+ "&eventEnd=" + endString
				+ "&remindTime=" + remindString
				+ "&locationKey=" + locationKeyString;
			new UpdateAsyncTask().execute(url) ;
			
		}
	};
	
	
	private class UpdateAsyncTask extends AsyncTask<String, String, String> {
		protected void onPreExecute() {
			if (pDialog != null) {
				pDialog = ProgressDialog.show(EventDetailsActivity.this, "", "Updating. Please wait...", true);
				pDialog.setCancelable(true);
				pDialog.setOnCancelListener(new OnCancelListener() {

					@Override
					public void onCancel(DialogInterface dialog) {
						cancel(true);
						pDialog.dismiss();
					}
				});
			}
			
		}

		protected String doInBackground(String... urls) {
			apiManager.connect(urls[0]);
			return "";
		}

		protected void onPostExecute(String result) {
			pDialog.dismiss();
				new AlertDialog.Builder(EventDetailsActivity.this)
				.setTitle("Update successful")
				.setMessage("event detail has been modified!")
				.setNeutralButton("OK", new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						finish();
						
					}
				}).show();
		}
	}
}
